package com.example.myaku.IPutil;

//这是一个用列表视图展示IP的适配器

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class IPAdapter extends RecyclerView.Adapter<IPAdapter.IPViewHolder> {
    private List<String> ipList = new ArrayList<>();
    private OnIPClickListener onIPClickListener;

    public interface OnIPClickListener {
        void onIPClick(String ip);
    }

    public void setOnIPClickListener(OnIPClickListener listener) {
        this.onIPClickListener = listener;
    }

    public void updateIpList(List<String> newIpList) {
        this.ipList.clear();
        this.ipList.addAll(newIpList);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public IPViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(android.R.layout.simple_list_item_1, parent, false);
        return new IPViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull IPViewHolder holder, int position) {
        String ip = ipList.get(position);
        holder.textView.setText(ip);

        holder.itemView.setOnClickListener(v -> {
            if (onIPClickListener != null) {
                onIPClickListener.onIPClick(ip);
            }
        });
    }

    @Override
    public int getItemCount() {
        return ipList.size();
    }

    static class IPViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        IPViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(android.R.id.text1);
        }
    }
}
